package com.czxy.controller;

import com.alibaba.fastjson.JSON;
import com.czxy.pojo.Category;
import com.czxy.pojo.group.BaseResult;
import com.czxy.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liuyunqin 17674029449@163.com
 * @date 2018/12/19 15:22
 */
@RestController
@RequestMapping
public class CategoryController {


    /**
     * redis缓存数据库
     */
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有首页分类
     * 弊端:根据id（221个）每次去请求数据库，
     *     请求数据库次数太多，获取连接和关闭连接消耗时间
     * @return
     */
   @GetMapping("categorys1")
   public ResponseEntity<Object> findAllCategory(){
       List<Category> allCategory = categoryService.findAllCategory();
       BaseResult baseResult= new BaseResult(0,"查询成功",allCategory);
       return ResponseEntity.ok(baseResult);
   }


    /**
     * 分类查询优化
     *   先读取所有的数据，减少获取连接和关闭连接的时间
     * @return
     */
    @GetMapping("categorys")
   public ResponseEntity<Object> findAll(){
       //0. 从缓存读取数据
        String categorys = redisTemplate.opsForValue().get("categorys");
        if (categorys!=null){
            return ResponseEntity.ok(categorys);
        }
        //1. 查询所有分类
       List<Category> all = categoryService.findAll();
       //2. 查询一级分类
       List<Category> category1 = findCategoryByParentId(0, all);
       //3.根据一级分类查询二级分类
       for (Category c1 : category1) {
           List<Category> category2 = findCategoryByParentId(c1.getId(), all);
           c1.setChildren(category2);
           //4. 根据二级分类查询三级分类
           for (Category c2 : category2) {
               List<Category> category3 = findCategoryByParentId(c2.getId(), all);
               c2.setChildren(category3);
           }
       }
       //5. 返回数据
       BaseResult baseResult= new BaseResult(0,"查询成功",category1);
       //6. 将所有分类放入redis中
        redisTemplate.opsForValue().set("categorys", JSON.toJSONString(baseResult));
       return ResponseEntity.ok(baseResult);
   }

    /**
     * 根据分类id 查
     * @param parentId
     * @param allList
     * @return
     */
   private List<Category> findCategoryByParentId(Integer parentId,List<Category> allList){
       //1. 定义变量，接收子分类
       List<Category> children = new ArrayList<>();
       //2. 遍历集合,找出子分类
       for (Category child : allList) {
           //判断
           if (child.getParentId()!=null&&child.getParentId().equals(parentId)) {
               children.add(child);
           }
       }
       //3. 返回数据
       return children;
   }
}
